<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\TallyClassModel;
use App\V3\V3_2_7\Services\TallyClassService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TallyClassController extends BaseController
{
    /**
     * 列表
     * AUTHOR  : Chen
     * DateTime: 2022/3/15 15:17
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        return $this->success(TallyClassService::index($this->getMainUserId()));
    }

    /**
     * 新建记账类型
     * @param Request $request
     * AUTHOR  : Chen
     * DateTime: 2022/3/15 15:23
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'name' =>'required|string',//记账类型名称
            'parent_id' =>'required|integer',//父id 一级为0
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        //验证记账类型是否存在
        $checkTallyClass = TallyClassService::checkTallyClass($data);
        if(!$checkTallyClass) {
            return $this->fail('', '记账类型'.$data['name'].'已存在，请重试');
        }

        $data['created_at'] = time();
        $logData = '记账分类：'.$data['name'].'创建成功';
        $id = TallyClassModel::insertGetId($data);
        $this->log('添加记账分类',$data, $logData);
        return $this->success($id);
    }

    public function edit(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//记账分类主键id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $name = TallyClassModel::where('id',$data['id'])->value('name');
        $logData = '记账分类：'.$name.'信息已更新！';
        TallyClassModel::where('id',$data['id'])->update($data);
        $this->log('编辑记账分类', $data, $logData);
        return $this->success();
    }

    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required',//记账分类主键id  多条用逗号分隔
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $name = TallyClassModel::where('id',$data['id'])->value('name');
        $logData = '记账分类：'.$name.'已删除！';
        TallyClassModel::destroy(explode(',',$data['id']));
        $this->log('删除记账分类', $data, $logData);
        return $this->success();
    }
}
